package com.gdcp.service.impl;

import com.gdcp.beans.Category;
import com.gdcp.beans.RoleUser;
import com.gdcp.beans.User;
import com.gdcp.common.Const;
import com.gdcp.common.ResponseModel;
import com.gdcp.config.RequestHolder;
import com.gdcp.config.annotation.RedisCache;
import com.gdcp.mapper.RoleUserMapper;
import com.gdcp.mapper.UserMapper;
import com.gdcp.service.RoleService;
import com.gdcp.service.RoleUserService;
import com.gdcp.util.ImageDto;
import com.gdcp.util.ImageUtil;
import com.gdcp.util.PathUtil;
import com.gdcp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    ResponseModel responseModel;
    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleUserService roleUserService;
    @Autowired
    RoleUserMapper roleUserMapper;

    @Override
    public Map<String, Object> login(String username, String password) {
        User user=userMapper.selectLogin(username, password);
        if (user==null){
            return responseModel.setModel(false,"输入账号密码错误");
        }
        return responseModel.setModel(true,user);
    }

    /*
    * 这个方法，使用在前台用户注册、以及后台的店长注册和管理员注册
    * 判断如果前台传来的shop_id为空，那么它就是前台注册的，（shop_id会自动生成0）
    * 店长和管理员的注册一致。
    * */
    @Transactional(rollbackFor = { Exception.class })
    @Override
    public Map<String, Object> register(User user) {
        Boolean usernameMap=this.checkValid(user.getUsername());
        if (!usernameMap){
            return responseModel.setModel(false,"注册失败,用户名已存在");
        }
        Boolean emailMap=this.checkValid(user.getEmail());
        if (!emailMap){
            return responseModel.setModel(false,"注册失败,email已存在");
        }

        //店长和管理员能指定权限，而前台就不行。
        if (user.getRole()==null){
            user.setRole(Const.Role.ROLE_USER);
        }

        User user1=(User) RequestHolder.getSession("user");
        //shop_id不用自己插入，数据库会自动生成0
        if (user1!=null){
            user.setShop_id(user1.getShop_id());
        }
        //插入权限
        userMapper.insert(user);

        //前台就是直接插入
        //后台就分为两个情况（一个），如果插入的用户已存在那么就提示该用户已存在（报错）
        //判断是否为4，如果是的话，那么就直接插入，如果不是那么还要查询一次
        RoleUser roleUser=roleUserService.getInformationByUserId(user.getId());
        if (roleUser!=null){
            RoleUser roleUser1=new RoleUser();
            roleUser1.setIuser_id(user.getId());
            roleUser1.setIrole_id(user.getRole());
            return roleUserService.updateInformation(roleUser);
        }

        int count=roleUserService.add(user.getId(),user.getRole());
        if (count<=0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return responseModel.setModel(false,"注册失败");
        }

        return responseModel.setModel(true,"注册成功");
    }

    @Override
    @Transactional(rollbackFor = { Exception.class })
    public Map<String,Object> updateInformation(User user) {
        /*if (user.getEmail()!=null) {
            int resultCount = userMapper.checkEmailByUserId(user.getEmail(), user.getId());
            if (resultCount>0){
                return responseModel.setModel(false,"email已存在，请更换email再更新");
            }
        }*/
        try{
            userMapper.updateByPrimaryKey(user);
            if (user.getRole()!=null){
                //User user1=(User)RequestHolder.getSession("user");
                System.out.println("user1.getId()="+user.getId());
                RoleUser roleUser1=roleUserService.getInformationByUserId(user.getId());
                if (roleUser1!=null){
                    RoleUser roleUser=new RoleUser();
                    roleUser.setId(roleUser1.getId());
                    roleUser.setIuser_id(user.getId());
                    roleUser.setIrole_id(user.getRole());
                    roleUserService.updateInformation(roleUser);
                    return responseModel.setModel(true,"修改成功");
                }
                roleUserService.add(user.getId(),user.getRole());
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return responseModel.setModel(false, "修改失败");
        }

        return responseModel.setModel(true,"修改成功");
    }

    @Override
    public Map<String,Object> updateHeadPortrait(User user, ImageDto image) {
        if(image!=null){
            User queryUser = userMapper.queryInfoById(user.getId());
            if(queryUser.getImage()!=null){
                ImageUtil.deleteFileOrPath(queryUser.getImage());
            }

            addThumbnail(queryUser, image);
            try{
                userMapper.updateThumbnailByPrimaryKey(queryUser);
            }catch (Exception e){
                e.printStackTrace();
                return responseModel.setModel(false,"修改头像失败");
            }

            RequestHolder.setSession("user",queryUser);
            return responseModel.setModel(true,"修改头像成功");

        }else{
            return responseModel.setModel(false,"图片获取不到");
        }
    }

    @Override
    @RedisCache(flush = true)
    public User getInformation(Integer userId) {
        return userMapper.queryInfoById(userId);
    }

    private void addThumbnail(User user, ImageDto image){
        // 获取图片存储路径
        String dest = PathUtil.getShopImagePath(user.getId());
        try {
            String imageAddr = ImageUtil.generateThumbnail(image,dest);
            user.setImage(imageAddr);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private Boolean checkValid(String str) {
        int usernameCount = userMapper.checkUsername(str).size();
        if(usernameCount > 0 ){
            //return responseModel.setModel(false,"注册失败,用户名已存在");
            return false;
        }

        int emailCount = userMapper.checkEmail(str).size();
        if(emailCount > 0 ){
            //return responseModel.setModel(false,"注册失败,email已存在");
            return false;
        }

        //return responseModel.setModel(true,"校验成功");
        return true;
    }

    @Override
    public Map<String,Object> findPageBreakByCondition(Map<String, Object> model, Integer shop_id) {
        //bootstrap-table要求服务器返回的json须包含：totlal，rows
        Map<String,Object> result = new HashMap<>();
        int total=userMapper.findPageBreakByConditionByShopId(shop_id).size();
        List<User> rows=userMapper.findPageBreakByCondition(model);
        if (rows.size()==0){
            int count= (int) model.get("a");
            count=count-(int) model.get("b");
            if (count>0){
                model.put("a",count);
                rows=userMapper.findPageBreakByCondition(model);
            }
        }
        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    @Override
    @Transactional(rollbackFor = { Exception.class })
    public Map<String,Object> removeByPrimaryKey(Integer[] ids) {
        try{
            for (Integer id:ids) {
                //查询下，是否有外键，评论【删掉】，店铺，收藏，权限
                //查询，店铺，收藏，权限
                RoleUser roleUser=roleUserMapper.getInformationByUserId(id);
                if (roleUser!=null){
                    roleUserMapper.removeByPrimaryKey(roleUser.getId());
                }
                userMapper.removeByPrimaryKey(id);
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return responseModel.setModel(false,"删除["+ids.length+"条记录失败"+e.toString());
        }

        return responseModel.setModel(true,"成功删除["+ids.length+"条记录");
    }

    /**
     * @Description: 搜索
     * @Param:
     * @return:
     * @Author: 杨华京
     */
    @Override
    public Map<String, Object> searchInformation(Map<String,Object> model) {
        Map<String,Object> result = new HashMap<>();
        int total=userMapper.searchInformation(null).size();
        List<User> rows=userMapper.searchInformation(model);
        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    @Override
    public int updateShopId(Integer shop_id,Integer user_id) {
        try{
            userMapper.updateShopId(shop_id,user_id);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public Map<String, Object> findAll(Map<String, Object> model) {
        Map<String,Object> result = new HashMap<>();
        int total=userMapper.findPageBreakByConditionByShopId(null).size();
        List<User> rows=userMapper.findAll(model);
        if (rows.size()==0){
            //System.out.println("11");
            //int count=Integer.valueOf(String.valueOf());
            int count= (int) model.get("a");
            count=count-(int) model.get("b");
            model.put("a",count);
            rows=userMapper.findAll(model);
        }
        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    @Override
    public Map<String, Object> searchInformationByShopId(Map<String, Object> model, Integer shop_id) {
        Map<String,Object> result = new HashMap<>();
        int total=userMapper.searchSizeByShopId(shop_id).size();
        List<Category> rows=userMapper.searchInformationByShopId(model);

        result.put("total",total);
        result.put("rows",rows);
        return result;
    }
}